﻿using System;
using System.IO;
using System.Windows.Forms;
using JavascriptWebResourcesManager.Forms.Solutions;
using Microsoft.Xrm.Sdk;

namespace JavascriptWebResourcesManager.Forms
{
    public partial class CreateScriptForm : Form
    {
        IOrganizationService innerService;

        SolutionManager sManager;

        public CreateScriptForm(IOrganizationService service)
        {
            InitializeComponent();

            this.innerService = service;
            this.sManager = new SolutionManager(this.innerService);
        }

        private void btnSelectSolution_Click(object sender, EventArgs e)
        {
            SolutionPicker sPicker = new SolutionPicker(innerService);
            sPicker.StartPosition = FormStartPosition.CenterParent;

            if (sPicker.ShowDialog(this) == DialogResult.OK)
            {
                this.sManager.CurrentSolution = sPicker.SelectedSolution;
                this.txtSelectedSolution.Text = this.sManager.CurrentSolution["friendlyname"].ToString();

                this.txtPrefix.Text = sManager.GetSolutionPrefix(((EntityReference)this.sManager.CurrentSolution["publisherid"]).Id);
                this.lblFullName.Text = string.Format("{0}_{1}", this.txtPrefix.Text, this.txtScriptName.Text);

                this.btnOk.Enabled = this.lblFullName.Text != this.txtPrefix.Text 
                                        && this.lblFullName.Text.Length > 0
                                        && this.txtPrefix.Text.Length > 0;
            }
        }

        private void txtScriptName_TextChanged(object sender, EventArgs e)
        {
            this.lblFullName.Text = string.Format("{0}_{1}", this.txtPrefix.Text, this.txtScriptName.Text);
            this.btnOk.Enabled = this.lblFullName.Text != this.txtPrefix.Text
                                       && this.lblFullName.Text.Length > 0
                                       && this.txtPrefix.Text.Length > 0;
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            Guid id = Guid.Empty;

            try
            {
                // Create script content
                MemoryStream ms = new MemoryStream();
                using (StreamWriter writer = new StreamWriter(ms))
                {
                    writer.WriteLine("// Script file created with JavaScript Web Resource Manager");
                    writer.WriteLine("// Add your script here");
                }

                // Create script entity
                Entity script = new Entity("webresource");
                script["content"] = Convert.ToBase64String(ms.ToArray());
                script["displayname"] = this.txtDisplayName.Text;
                script["description"] = this.txtDescription.Text;
                script["name"] = this.lblFullName.Text;
                script["webresourcetype"] = new OptionSetValue(3);

                id = this.innerService.Create(script);
            }
            catch (Exception error)
            {
                MessageBox.Show(this, "Error while creating script: " + error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            if (id != Guid.Empty)
            {
                try
                {
                    this.sManager.AddComponent(61, id);
                }
                catch (Exception error)
                {
                    MessageBox.Show(this, string.Format(
                        "Error while adding script to the selected solution: {0}\r\n\r\nNevertheless, the script has been created.",
                        error.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
            }
           
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }
    }
}
